package com.inno.subject.domain.strategy.subject;

import com.inno.subject.common.error.BusinessException;
import com.inno.subject.domain.entity.SubjectInfoBO;
import com.inno.subject.domain.entity.SubjectTypeBO;
import com.inno.subject.domain.service.SubjectTypeDomainService;
import com.inno.subject.domain.utils.ChatClientUtil;
import com.inno.subject.infra.basic.entity.PlannerSubjectInfo;
import com.inno.subject.infra.basic.service.PlannerSubjectInfoService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author shenzeyang
 */
@Component
public class ShortAnswerSubjectHandler implements SubjectHandler{
    @Resource
    private SubjectTypeDomainService subjectTypeDomainService;
    @Resource
    private PlannerSubjectInfoService plannerSubjectInfoService;
    @Resource
    private ThreadPoolTaskExecutor subjectExecutor;
    @Resource
    private ChatClientUtil chatClientUtil;

    private Long subjectType;

    @PostConstruct
    public void init(){
        this.subjectType = this.querySubjectType().getId();
    }
    @Override
    public Long getTypeId() {
        return this.subjectType;
    }

    @Override
    public void handle(SubjectInfoBO subjectInfoBO, PlannerSubjectInfo entity) {
        this.saveSubject(plannerSubjectInfoService,entity);
        CompletableFuture.runAsync(() -> {
            String parse = chatClientUtil.buildSubjectParsePrompt(entity.getSubjectName());
            String response = chatClientUtil.call(parse);
            PlannerSubjectInfo info = new PlannerSubjectInfo();
            info.setId(entity.getId());
            info.setSubjectParse(response);
            this.plannerSubjectInfoService.update(info);
        }, subjectExecutor);
    }


    @Override
    public SubjectTypeBO querySubjectType() {
        List<SubjectTypeBO> subjectTypeBOList = subjectTypeDomainService.queryList();
        return subjectTypeBOList
                .stream()
                .filter(subjectTypeBO -> "简答题".equals(subjectTypeBO.getTypeName()))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("cannot init this class(ShortAnswerSubjectHandler) because current type(简答题) not found. please check your datasource!"));
    }
}
